package com.yy.app.config.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;

/**
 * @Description 细的日志记录
 * @Date 2025/10/11 上午10:17
 * @Author yanglin
 **/
public class LoggingTokenResponseClient implements OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> {

    private static final Logger logger = LoggerFactory.getLogger(LoggingTokenResponseClient.class);
    private final OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> delegate;

    public LoggingTokenResponseClient(OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> delegate) {
        this.delegate = delegate;
    }

    @Override
    public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationGrantRequest) {
        logger.info("[SSO-AUTH-APP2] Requesting token from: {}", authorizationGrantRequest.getClientRegistration().getProviderDetails().getTokenUri());
        logger.info("[SSO-AUTH-APP2] Client ID: {}", authorizationGrantRequest.getClientRegistration().getClientId());
        logger.info("[SSO-AUTH-APP2] Client Secret: {}", authorizationGrantRequest.getClientRegistration().getClientSecret());
        logger.info("[SSO-AUTH-APP2] Grant type: {}", authorizationGrantRequest.getGrantType().getValue());
        logger.info("[SSO-AUTH-APP2] Code: {}", authorizationGrantRequest.getAuthorizationExchange().getAuthorizationResponse().getCode());
        logger.info("[SSO-AUTH-APP2] Redirect URI: {}", authorizationGrantRequest.getAuthorizationExchange().getAuthorizationRequest().getRedirectUri());

        try {
            OAuth2AccessTokenResponse response = delegate.getTokenResponse(authorizationGrantRequest);
            logger.info("[SSO-AUTH-APP2] Token response received: {}", response.getAccessToken().getTokenValue());
            return response;
        } catch (Exception e) {
            logger.error("[SSO-AUTH-APP2] Token request failed", e);
            throw e;
        }
    }
}
